const state = {
  time: new Date(), // 当前时间(实时更新)
  schedule: undefined, // 任务执行器
  scheduleMap: new Map() // 分发
}

const mutations = {
  initSchedule: (state) => {
    if (state.schedule === undefined) {
      state.schedule = setInterval(() => {
        state.time = new Date()
        state.scheduleMap.forEach(item => {
          const date = new Date().getTime()
          if ((date - item.lastTime) > item.timer) {
            item.lastTime = date
            Promise.resolve().then(item.schedule)
          }
        })
      }, 200)
    }
  },
  addSchedule(state, params) {
    const { name, schedule, timer = 1000 } = params
    console.info('添加任务执行器：', params)
    if (!(schedule instanceof Function)) {
      throw new Error('schedule参数类型错误，请传入回调函数')
    }
    if (isNaN(timer)) {
      throw new Error('timer参数类型错误，请传入数值，单位毫秒')
    }
    state.scheduleMap.set(name, {
      schedule,
      timer,
      lastTime: new Date().getTime() // 上次执行时间毫秒
    })
  },
  removeSchedule(state, name) {
    console.info('移除任务执行器：' + name)
    state.scheduleMap.delete(name)
  }
}

export default {
  namespaced: true,
  state,
  mutations
}
